import cv2 as cv
from matplotlib import pyplot as plt
img_rice_path = "rice.png"
img_rice = cv.imread(img_rice_path)
plt.hist(img_rice.ravel(), 256, [0, 256])
plt.show()

rice_gray = cv.cvtColor(img_rice, cv.COLOR_BGR2GRAY)
# 大津算法阈值化
_, bw = cv.threshold(rice_gray, 0, 0xff, cv.THRESH_OTSU)
# 去除噪声
element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))
bw = cv.morphologyEx(bw, cv.MORPH_OPEN, element)
cv.imshow("t", bw)
cv.waitKey()
cv.destroyAllWindows()
